package dk.snaveponyklub.persist.impl;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

//import javax.xml.transform.Source;
//import javax.xml.transform.dom.DOMSource;
//import javax.xml.validation.*;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.SAXException;

public class XMLValidator {

	public boolean isValid(Document document, String xsdFilename) {
        try {
			// Do validation against schema
	        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
	        URL fileUrl = getClass().getClassLoader().getResource(xsdFilename);
	        File schemaLocation = new File(fileUrl.toURI());
	        Schema schema = factory.newSchema(schemaLocation);
	        String xml = extractXML(document);
	        Source xmlSource = new StreamSource(new CharArrayReader(xml.toCharArray()));
	        Validator validator = schema.newValidator();
            validator.validate(xmlSource);
            return true;
        }
        catch (SAXException ex) {
            System.out.println(" is not valid because ");
            System.out.println(ex.getMessage());
        }  
        catch (Exception ex) {
            System.out.println(ex.getMessage());
        }  
		return false;
	}
	
	public Document buildAndValidate(String xml, String xsdFilename) {		
		SAXBuilder builder = new SAXBuilder();
        try {
			// Do validation against schema
	        URL schemaFileUrl = getClass().getClassLoader().getResource(xsdFilename);
			File schemaLocation = new File(schemaFileUrl.toURI());			
			builder.setValidation(true);
			builder.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
			builder.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaLocation);
	        Document document = builder.build(new CharArrayReader(xml.toCharArray()));
            return document;
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
	}

	public boolean isValid(String xml, String xsdFilename) {
        try {
	        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
	        URL fileUrl = getClass().getClassLoader().getResource(xsdFilename);
	        File schemaLocation = new File(fileUrl.toURI());
	        Schema schema = factory.newSchema(schemaLocation);
	        Source xmlSource = new StreamSource(new CharArrayReader(xml.toCharArray()));
	        Validator validator = schema.newValidator();
            validator.validate(xmlSource);
            return true;
        }
        catch (SAXException ex) {
            System.out.println(" is not valid because ");
            System.out.println(ex.getMessage());
        }  
        catch (Exception ex) {
            System.out.println(ex.getMessage());
        }  
        return true;
	}
	
	public static String extractXML(Document document) {
		String xml = null;
		XMLOutputter xo = new XMLOutputter();
        Format format = Format.getPrettyFormat();
        format.setEncoding("UTF-8");
        xo.setFormat(format);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            xo.output(document, baos);
            xml = baos.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xml;
	}	

	public static void main(String[] args) throws IOException {
//	    Namespace ns = Namespace.getNamespace("s", "http://www.snaveponyklub.dk");
//	    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
//    	Document person = new Document();
//        Element student = new Element("person", ns);
//        student.addNamespaceDeclaration(xsi);
//        student.setAttribute("type", "s:studenttype", xsi);
//        student.setAttribute("id", "3");
//        student.addContent(new Element("name", ns).setText("Niels"));
//        student.addContent(new Element("lastname", ns).setText("Bock"));
//        student.addContent(new Element("username", ns).setText("Bock"));
//        student.addContent(new Element("password", ns).setText("pass"));
//        person.setRootElement(student);
//        cache.addPerson(person);
        Document document = new XMLLoaderImpl().loadPersonsDocument();
        String xml = extractXML(document);
    	System.out.println("Valid: " + new XMLValidator().isValid(xml, "Persist.xsd"));
    	System.out.println("Valid: " + new XMLValidator().isValid(document, "Persist.xsd"));
    	System.out.println("Valid: " + new XMLValidator().buildAndValidate(xml, "Persist.xsd"));
        xml = extractXML(document);
    	System.out.println(xml);
        
    	
    	
//        String xml = "<?xml version='1.0' encoding='UTF-8'?><s:persist xmlns:s='http://www.snaveponyklub.dk'><s:timeslots><s:timeslot endtime='2010-10-05T10:00:00' starttime='2010-10-05T11:00:00' id='4'></s:timeslot></s:timeslots></s:persist>";
//    	System.out.println("Validate: " + new XMLValidator().validate(xml, "Persist.xsd"));
    }	

}
